const db = require('../../db')
const bcrypt = require('bcryptjs')

/**
 * 创建新用户
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.createUser = (req, res) => {
    const { username, password, email, phone, status = 1 } = req.body
    // 验证必填字段
    if (!username || !password) {
        return res.status(400).json({ code: 400, message: '用户名和密码为必填项' })
    }
    // 验证状态值
    if (![0, 1].includes(Number(status))) {
        return res.status(400).json({ code: 400, message: '状态值无效，必须为0或1' })
    }
    // 检查用户名是否已存在
    const checkSql = 'select * from users where username = ?'
    db.query(checkSql, [username], (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        if (results.length > 0) return res.status(400).json({ code: 400, message: '用户名已存在' })
        // 密码加密
        const salt = bcrypt.genSaltSync(10)
        const hashedPassword = bcrypt.hashSync(password, salt)
        // 插入新用户
        const insertSql = 'insert into users (username, password, email, phone, status, created_at, updated_at) values (?, ?, ?, ?, ?, NOW(), NOW())'
        db.query(insertSql, [username, hashedPassword, email || null, phone || null, status], (err, result) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            res.status(200).json({
                code: 200,
                message: '用户创建成功',
            })
        })
    })
}

/**
 * 更新用户状态
 * @param {*} req
 * @param {*} res
*/
exports.updateUserStatus = (req, res) => {
    const { id, status } = req.body
    // 验证必填字段
    if (!id) {
        return res.status(400).json({ code: 400, message: '用户ID为必填项' })
    }
    // 验证状态值
    if (![0, 1].includes(Number(status))) {
        return res.status(400).json({ code: 400, message: '状态值无效，必须为0或1' })
    }
    // 检查用户是否存在
    const checkSql = 'select * from users where id = ?'
    db.query(checkSql, [id], (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        if (results.length === 0) return res.status(404).json({ code: 404, message: '用户不存在' })
        // 更新用户状态
        const updateSql = 'update users set status = ?, updated_at = NOW() where id = ?'
        db.query(updateSql, [status, id], (err, result) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            res.status(200).json({
                code: 200,
                message: '用户状态更新成功',
            })
        })
    })
}

/**
 * 获取用户列表
 * @param {*} req
 * @param {*} res
 * 
 */
exports.getUserList = (req, res) => {
    const page = parseInt(req.query.page) || 1
    const pageSize = parseInt(req.query.pageSize) || 10
    const offset = (page - 1) * pageSize
    const username = req.query.username
    const status = req.query.status

    // 构建WHERE子句
    let whereClause = ''
    let params = []
    // 根据用户名查询
    if (username && username.trim() !== '') {
        whereClause += 'username LIKE ? '
        params.push(`%${username}%`)
    }
    // 根据状态查询
    if (status !== undefined && status !== '') {
        whereClause += whereClause ? 'AND status = ? ' : 'status = ? '
        params.push(status)
    }
    whereClause = whereClause ? 'WHERE ' + whereClause : ''

    // 查询总数
    const countSql = `select count(*) as total from users ${whereClause}`
    db.query(countSql, params, (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        const total = results[0].total

        // 分页查询数据，返回除密码外的所有字段
        const sql = `select id, username, email, phone, status, created_at, updated_at from users ${whereClause}limit ?, ?`
        db.query(sql, [...params, offset, pageSize], (err, results) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            res.status(200).json({
                code: 200,
                message: '获取用户列表成功',
                data: {
                    total,
                    list: results,
                    page,
                    pageSize
                }
            })
        })
    })
}

/**
 * 编辑用户信息
 * @param {*} req
 * @param {*} res
 */
exports.editUser = (req, res) => {
    const { id, username, email, phone } = req.body
    // 验证必填字段
    if (!id) {
        return res.status(400).json({ code: 400, message: '用户ID为必填项' })
    }
    if (!username) {
        return res.status(400).json({ code: 400, message: '用户名为必填项' })
    }

    // 检查用户是否存在
    const checkUserSql = 'select * from users where id = ?'
    db.query(checkUserSql, [id], (err, results) => {
        if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
        if (results.length === 0) return res.status(404).json({ code: 404, message: '用户不存在' })

        // 检查新用户名是否与其他用户重复
        const checkUsernameSql = 'select * from users where username = ? and id != ?'
        db.query(checkUsernameSql, [username, id], (err, results) => {
            if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
            if (results.length > 0) return res.status(400).json({ code: 400, message: '用户名已存在' })

            // 更新用户信息
            const updateSql = 'update users set username = ?, email = ?, phone = ?, updated_at = NOW() where id = ?'
            db.query(updateSql, [username, email || null, phone || null, id], (err, result) => {
                if (err) return res.status(500).json({ code: 500, message: '服务器错误：' + err.message })
                res.status(200).json({
                    code: 200,
                    message: '用户信息更新成功',
                })
            })
        })
    })
}